package org.apache.guacamole.auth;

import com.google.inject.Guice;
import com.google.inject.Injector;
import org.apache.guacamole.GuacamoleException;
import org.apache.guacamole.net.auth.AbstractAuthenticationProvider;
import org.apache.guacamole.net.auth.AuthenticatedUser;
import org.apache.guacamole.net.auth.Credentials;
import org.apache.guacamole.net.auth.UserContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Allows users to be authenticated using encrypted blobs of JSON data. The
 * username of the user, all available connections, and the parameters
 * associated with those connections are all determined by the contents of the
 * provided JSON. The JSON itself is authorized by virtue of being properly
 * encrypted with a shared key.
 */
public class ArchempowerAuthenticationProvider extends AbstractAuthenticationProvider {

    private static final Logger logger = LoggerFactory.getLogger(ArchempowerAuthenticationProvider.class);


    /**
     * Injector which will manage the object graph of this authentication
     * provider.
     */
    private final Injector injector;

    /**
     * Creates a new JSON AuthenticationProvider that authenticates users
     * using encrypted blobs of JSON data.
     *
     * @throws GuacamoleException
     *     If a required property is missing, or an error occurs while parsing
     *     a property.
     */
    public ArchempowerAuthenticationProvider() throws GuacamoleException {

        // Set up Guice injector.
        injector = Guice.createInjector(new ArchempowerAuthenticationProviderModule(this));

    }

    @Override
    public String getIdentifier() {
        return "archempower";
    }

    @Override
    public AuthenticatedUser authenticateUser(Credentials credentials) throws GuacamoleException {

        logger.debug("{}.authenticateUser: {}, {}",
                this.getIdentifier(),
                credentials.getUsername(),
                credentials.getPassword());

        AuthenticationProviderService authProviderService = injector.getInstance(AuthenticationProviderService.class);
        return authProviderService.authenticateUser(credentials);

    }

    @Override
    public UserContext getUserContext(AuthenticatedUser authenticatedUser)
            throws GuacamoleException {

        AuthenticationProviderService authProviderService = injector.getInstance(AuthenticationProviderService.class);
        return authProviderService.getUserContext(authenticatedUser);

    }

}
